<?php

namespace App\Http\Controllers\Admin;

use App\Service\AdminService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    private $service;

    public function __construct(AdminService $service)
    {
        $this->service = $service;
    }

    /**
     * 登录验证
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request)
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
        {
            $admin = $this->service->repository->where('email', $request->email)->first();
            $data =  $admin->createToken(config('app.name').'Admin')->accessToken;
            return $this->code(['token' => $data, 'admin' => $admin]);
        } else {
            return $this->getError(401);
        }
    }

    /**
     * @author huangangui
     * @explain 获取所有用户
     * @return mixed
     */
    public function index(){
        $data = $this->service->repository->orderBy('id', 'desc')->paginate($this->page);
        return $this->code($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $this->service->repository->create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);
        return $this->code($data);
    }
}
